#coding=utf-8
from django.shortcuts import render
from models import *
from django.http import HttpResponse
from django.views.decorators.csrf import ensure_csrf_cookie

# Create your views here.
def index(request):

    # hero = HeroInfo.objects.get(pk =1 )
    list = HeroInfo.objects.filter(isDelete=True)
    return render(request, 'booktest/index.html', locals())

def show(request, id, ia):
    return render(request, 'booktest/show.html', locals())

def index2(request):
    return render(request, 'booktest/index2.html', locals())


def user1(request):
    uname = 'xidada'
    return render(request, 'booktest/user1.html', locals())
def user2(request):
    return render(request, 'booktest/user2.html')


def htmlTest(request):
    t1 = '<h1>123<h1>'
    return render(request, 'booktest/htmlTest.html', locals())

@ensure_csrf_cookie
def csrf1(request):
    return render(request, 'booktest/csrf1.html', locals())

def csrf2(request):
    uname = request.POST['uname']
    return HttpResponse(uname)

def verifycode(request):
    from PIL import Image,ImageDraw,ImageFont
    import random

    bgcolor = (random.randrange(20,200),random.randrange(50,100),0)
    width = 100
    height = 25
    # 创建画面对象
    im = Image.new('RGB', (width, height), bgcolor)
    # 创建画笔对象
    draw = ImageDraw.Draw(im)
    # 调用画笔的point()函数绘制噪点
    for i in range(0, 100):
        xy = (random.randrange(0, width), random.randrange(0, height))
        fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
        draw.point(xy, fill=fill)
    # 定义验证码的备选值
    str1 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0'
    # 随机选取4个值作为验证码
    rand_str = ''
    for i in range(0, 4):
        rand_str += str1[random.randrange(0, len(str1))]
    # 构造字体对象
    font = ImageFont.truetype('FreeMono.ttf', 24)
    # 构造字体颜色
    fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
    # 绘制4个字
    draw.text((5, 2), rand_str[0], font=font, fill=fontcolor)
    fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
    draw.text((25, 2), rand_str[1], font=font, fill=fontcolor)
    fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
    draw.text((50, 2), rand_str[2], font=font, fill=fontcolor)
    fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
    draw.text((75, 2), rand_str[3], font=font, fill=fontcolor)
    # 释放画笔
    del draw
    # 存入session，用于做进一步验证
    request.session['code'] = rand_str
    # 内存文件操作
    import cStringIO
    buf = cStringIO.StringIO()
    # 将图片保存在内存中，文件类型为png
    im.save(buf, 'png')
    # 将内存中的图片数据返回给客户端，MIME类型为图片png
    return HttpResponse(buf.getvalue(), 'image/png')
